package czy.demo.controller;

import czy.demo.pojo.Person;
import czy.demo.repository.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/repository")
public class RepositoryController {

    private static final Logger logger = LoggerFactory.getLogger(RepositoryController.class);

    @Autowired
    private PersonRepository personRepository;

    @GetMapping("/all")
    public List<Person> findAll(){
        return this.personRepository.findAll();
    }

    @GetMapping("/get/{id}")
    public Person findById(@PathVariable Integer id){
        return this.personRepository.findById(id).get();
    }

    @GetMapping("/name/{name}")
    public Person findByName(@PathVariable String name){
        return this.personRepository.findByName(name);
    }

    @GetMapping("/exists/{id}")
    public boolean exists(@PathVariable Integer id){
        return this.personRepository.existsById(id);
    }

    /**
     * 分页查询
     * @param page：页码，这里的页码从0开始
     * @param size：分页大小
     * @param sort：排序字段
     * @return
     */
    @GetMapping("/page")
    public Page page(
            @RequestParam Integer page,
            @RequestParam Integer size,
            @RequestParam(required = false,defaultValue = "id") String sort
    ){
        Sort s = Sort.by(sort);
        Pageable pageable = PageRequest.of(page,size,s);
        return this.personRepository.findAll(pageable);
    }

    @PostMapping("/insert")
    public String insert(@RequestBody Person person){
        /* 插入重复主键会报错 */
        this.personRepository.insert(person);
        return "插入成功";
    }

    @PostMapping("/insert/many")
    public String insert(@RequestBody List<Person> persons){
        this.personRepository.insert(persons);
        return "插入成功";
    }

    @PutMapping("/update")
    public Person update(@RequestBody Person person){
        this.personRepository.save(person);
        return person;
    }

    @DeleteMapping("/delete/{id}")
    public Person delete(@PathVariable Integer id){
        Person person = this.personRepository.findById(id).get();
        this.personRepository.deleteById(id);
        return person;
    }

    @DeleteMapping("/delete/all")
    public String deleteAll(){
        this.personRepository.deleteAll();
        return "删除所有实体成功";
    }
}
